package com.glorious.gcontacts.login.spring.controllers;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.glorious.gcontacts.login.data.GoogleContactsAppData;
import com.glorious.gcontacts.model.GoogleContactInfo;
import com.glorious.gcontacts.model.UserData;
import com.glorious.gcontacts.spring.services.UsersService;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;

@Controller
@RequestMapping("/gcontacts")
public class GoogleContactsLoginController
{
	private UsersService usersService;
	
	@Autowired
	public void setUsersService(UsersService usersService)
	{
		this.usersService = usersService;
	}
	
	@RequestMapping("/auth")
	public void auth(@RequestParam String back, HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
		oauthParameters.setOAuthConsumerKey(GoogleContactsAppData.CONSUMER_KEY);
		oauthParameters.setOAuthConsumerSecret(GoogleContactsAppData.CONSUMER_SECRET);
		oauthParameters.setScope("https://www.google.com/m8/feeds/contacts");
		String server = request.getServerPort() == 80 ? "www.gloriouscontacts.com" : "localhost:" + request.getServerPort();
		oauthParameters.setOAuthCallback(String.format("http://%s/login/gcontacts/approved", server));

		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
		try
		{
			oauthHelper.getUnauthorizedRequestToken(oauthParameters);
		} catch (OAuthException e)
		{
			e.printStackTrace();
		}

		String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
		response.addCookie(new Cookie("token_secret", oauthParameters.getOAuthTokenSecret()));
		response.addCookie(new Cookie("back_url", back));
		response.sendRedirect(approvalPageUrl);
	}

	@RequestMapping("/approved")
	public void approved(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
		oauthParameters.setOAuthConsumerKey(GoogleContactsAppData.CONSUMER_KEY);
		oauthParameters.setOAuthConsumerSecret(GoogleContactsAppData.CONSUMER_SECRET);

		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
		oauthHelper.getOAuthParametersFromCallback(request.getQueryString(), oauthParameters);

		for (Cookie cookie : request.getCookies())
		{
			if (cookie.getName().equals("token_secret"))
			{
				oauthParameters.setOAuthTokenSecret(cookie.getValue());
				break;
			}
		}
		
		try
		{
			User user = UserServiceFactory.getUserService().getCurrentUser();
			UserData data = usersService.getUserData(user);
			data.setGoogleContactInfo(new GoogleContactInfo(oauthHelper.getAccessToken(oauthParameters), oauthParameters.getOAuthTokenSecret()));
			usersService.updateUserData(data);
			for (Cookie cookie : request.getCookies())
			{
				if (cookie.getName().equals("back_url"))
				{
					response.sendRedirect(cookie.getValue());
					break;
				}
			}
		} 
		catch (OAuthException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
